package cn.walls1717.juc.interrupt;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 中断机制测试<br>
 *
 * @author walls1717
 * @create 2022/12/10 13:32
 **/
@Slf4j
public class InterruptDemo {

    static volatile boolean isStop = false;
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public static void main(String[] args) throws InterruptedException {
        // m1();
        // m2();

        /*
        使用interrupt与isInterrupted组合打断线程
         */
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    log.info("isInterrupted为true，程序停止");
                    break;
                }
                log.info("isInterrupted为false");
            }
        }, "t1");
        t1.start();

        TimeUnit.MILLISECONDS.sleep(10);

        new Thread(() -> {
            t1.interrupt();
        }, "t2").start();
    }

    /**
     * 使用原子类打断线程
     *
     * @throws InterruptedException 。
     */
    private static void m2() throws InterruptedException {
        new Thread(() -> {
            while (true) {
                if (atomicBoolean.get()) {
                    log.info("isStop为true，程序停止");
                    break;
                }
                log.info("isStop为false");
            }
        }, "t1").start();

        TimeUnit.MILLISECONDS.sleep(10);

        new Thread(() -> {
            atomicBoolean.set(true);
        }, "t2").start();
    }

    /**
     * 使用volatile保证可见性打断线程
     *
     * @throws InterruptedException 。
     */
    private static void m1() throws InterruptedException {
        new Thread(() -> {
            while (true) {
                if (isStop) {
                    log.info("isStop为true，程序停止");
                    break;
                }
                log.info("isStop为false");
            }
        }, "t1").start();

        TimeUnit.MILLISECONDS.sleep(5);

        new Thread(() -> {
            isStop = true;
        }, "t2").start();
    }
}
